package com.JDK.Lock;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

public class CycleBarrierDemo {



    public static void main(String[] args) {
        CyclicBarrier cyclicBarrier = new CyclicBarrier(3,new TourGuideTask());
        Executor executor =  Executors.newFixedThreadPool(3);

        executor.execute(new TravelTask(cyclicBarrier,"张三", (int) (Math.random() * 10000)));
        executor.execute(new TravelTask(cyclicBarrier,"李四", (int) (Math.random() * 10000)));
        executor.execute(new TravelTask(cyclicBarrier,"王五", (int) (Math.random() * 10000)));

    }


    private static class TravelTask implements  Runnable{
        private CyclicBarrier cycleBarrier;
        private  String name;
        private int arriveTime;

        public TravelTask(CyclicBarrier  cycleBarrier, String name, int arriveTime) {
            this.cycleBarrier = cycleBarrier;
            this.name = name;
            this.arriveTime = arriveTime;
        }

        @Override
        public void run() {
            try{
                Thread.sleep(arriveTime);
                System.out.println(name + "到达集合点");
                this.cycleBarrier.await();
                System.out.println("人都到齐啦，那么我们开始旅行吧！！");
            }catch (InterruptedException | BrokenBarrierException e){
                e.printStackTrace();
            }
        }
    }

    private static class TourGuideTask implements Runnable{

        @Override
        public void run() {
            System.out.println("****导游分发护照签证****");
            try {
                //模拟发护照签证需要2秒
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
